const fs = require('fs')
const Payment = require('wechat-pay').Payment
const Pay = require('wechat-pay-api')

const initConfig = {
  partnerKey: 'bf3ce93dd3c6552bd92e3d84db1cb640',
  appId: 'wx69c3c1b9b3a78949',
  mchId: '1491082592',
  notifyUrl: 'http://wxpay.wxlai.com/pay/callback',
  pfx: fs.readFileSync(__dirname + '/apiclient_cert.p12')
}

const pay = new Pay({
  wxappid: 'wx69c3c1b9b3a78949',
  mch_id: '1491082592',
  key: 'bf3ce93dd3c6552bd92e3d84db1cb640',
  pfx: fs.readFileSync(__dirname + '/apiclient_cert.p12'),
  client_ip: '120.24.182.124'
})

const payment = new Payment(initConfig)

function getNonceStr () {
  return Math.random().toString().slice(2, 32)
}

function getBillno () {
  return (Date.now() + '' + getNonceStr()).slice(0, 28)
}

Parse.Cloud.define('getPayConfig', async (req, res) => {
  const {id, type} = req.params
  try {
    const order = {
      body: '',
      product_id: '',
      out_trade_no: getBillno(),
      total_fee: '',
      spbill_create_ip: '120.24.182.124',
      trade_type: 'APP'
    }
    if (type === 'vip') {
      const q = new Parse.Query('RcVip').include('circle')
      const vip = await q.get(id)
      order.body = `${vip.get('circle').get('name')}圈${vip.get('months')}个月VIP`
      order.product_id = vip.id
      order.total_fee = vip.get('price') * 100
    } else {
      const q = new Parse.Query('RcResource')
      const resource = await q.get(id)
      order.body = resource.get('title')
      order.product_id = resource.id
      order.total_fee = resource.get('price') * 100
    }
    if (order.product_id && order.total_fee) {
      payment.unifiedOrder(order, function (error, result) {
        if (error) {
          console.log(error)
          res.error(error.message)
        } else {
          console.log(result)

          const timeStamp = Math.round((new Date()).getTime() / 1000)
          const data = {
            openID: initConfig.appId,
            partnerId: '1491082592',
            prepayId: result.prepay_id,
            nonceStr: result.nonce_str,
            timeStamp: timeStamp,
            package: 'Sign=WXPay'
          }

          const options = {
            appid: initConfig.appId,
            partnerid: '1491082592',
            prepayid: result.prepay_id,
            noncestr: result.nonce_str,
            timestamp: timeStamp,
            package: 'Sign=WXPay'
          }

          data.sign = pay.getSign(options)

          res.success(data)
        }
      })
    } else {
      res.error('找不到指定的资源')
    }
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }


})

